package com.gk.javaservice.realm;


import com.gk.javaservice.po.AdminUsers;
import com.gk.javaservice.service.AdminUsersService;
import com.gk.javaservice.util.MD5Encryption;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * 自定义Realm，实现授权与认证
 */
public class UserRealm extends AuthorizingRealm {

    @Resource
    private AdminUsersService userService;

    private Logger log = Logger.getLogger(this.getClass());

    /**
     * 用户授权
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principalCollection) {

//        log.info("===执行授权===");
        //获取登陆的对象
        Object id = principalCollection.fromRealm(getName()).iterator().next();
        AdminUsers user = userService.hasById(id);
//        log.info(user);
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            // 角色与权限字符串集合
//            Collection<String> rolesCollection = new HashSet<>();
//            Collection<String> premissionCollection = new HashSet<>();
//            // 读取并赋值用户角色与权限
//            Set<Roles> roles = user.getRoles();
//            for(Roles role : roles){
//                rolesCollection.add(role.getRolesName());
//                Set<Permission> permissions = role.getPermissions();
//                for (Permission permission : permissions){
//                    premissionCollection.add(permission.getUrl());
//                }
//                info.addStringPermissions(premissionCollection);
//            }

            //添加权限名称
            info.addRole(user.getAdminRoles().getSlug());
//            info.addStringPermission("vip");
//            info.addStringPermission("mvp");

//            log.info("user.getRole().getRoleName():" + user.getAdminRoles().getName());
//            log.info("info.getStringPermissions():" + info.getStringPermissions());
            return info;
        }
        return null;
    }


    /**
     * 用户认证
     **/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {

        log.info("===执行认证===");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        AdminUsers bean = new AdminUsers();
        bean.setUsername(token.getUsername());
        bean.setPassword(String.valueOf(token.getPassword()));
        bean = userService.login(bean);
//        log.info(bean);
//        log.info("String.valueOf(token.getPassword()):" + String.valueOf(token.getPassword()));
        if (bean == null) {
            throw new UnknownAccountException();
        }
        //MD5加密处理
        String pwd = MD5Encryption.encryption(String.valueOf(token.getPassword()), 1, null, null);
        //String pwd= String.valueOf(token.getPassword());
        bean.setPassword(pwd);
//        log.info(pwd + ":bean.getPass():" + bean.getPassword());
//        log.info(pwd.equals(bean.getPassword()));
        if (pwd.equals(bean.getPassword())) {
//            log.info("in to if");

            Session session = SecurityUtils.getSubject().getSession();


            session.setAttribute("loginUser", bean);
            session.setAttribute("username", bean.getUsername());
            session.setTimeout(43200000);

            ByteSource credentialsSalt = ByteSource.Util.bytes("");

//            log.info("bean.getName():" + bean.getUsername());
//            bean.setPassword(String.valueOf(token.getPassword()));
            //ByteSource credentialsSalt = ByteSource.Util.bytes(bean.getName());
            return new SimpleAuthenticationInfo(bean, bean.getPassword(),
                    credentialsSalt, getName());
        } else {
            return null;
        }
//        return new SimpleAuthenticationInfo(bean, bean.getPwd(),
//                credentialsSalt, getName());

    }

    // 模拟Shiro用户加密，假设用户密码为123456
    public static void main(String[] args) {
        // 用户名
        String username = "rhine";
        // 用户密码
        String password = "123456";
        // 加密方式
        String hashAlgorithName = "MD5";
        // 加密次数
        int hashIterations = 8;
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        Object obj = new SimpleHash(hashAlgorithName, password,
                credentialsSalt, hashIterations);
        // System.out.println("------------------------------------main-----------------------------------");
        // System.out.println(obj);
        // System.out.println("------------------------------------main-----------------------------------");
    }
}
